package com.woniu.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;

import java.io.File;
import java.io.InputStream;

public class OssUtils {

    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    private static String endpoint = "oss-cn-chengdu.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    private static String accessKeyId = "LTAI5t8D8kBUXSrg5AeF368o";

    private static String accessKeySecret = "BjfIVconzil6Bmq0HuXrt2BZoVQYUE";


    //文件上传（文件对象）
    public static String upload(String bucketName, String fileName, File file){
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, fileName, file);
            return "http://" + bucketName + "." + endpoint + "/" + fileName;
        }  finally {
            // 关闭OSSClient。
            if(ossClient!=null) ossClient.shutdown();
        }
    }

    //文件上传（读取流）
    public static String upload(String bucketName, String fileName,InputStream file){
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            PutObjectResult result = ossClient.putObject(bucketName, fileName, file);
            return "http://" + bucketName + "." + endpoint + "/" + fileName;
        }  finally {
            // 关闭OSSClient。
            if(ossClient!=null) ossClient.shutdown();
        }
    }


    //文件删除
    public static void deleteFile(String bucketName, String filePathName){
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
             ossClient.deleteObject(bucketName,filePathName);
        }  finally {
            // 关闭OSSClient。
            if(ossClient!=null) ossClient.shutdown();
        }
    }
}
